#!/usr/bin/python
# -*- coding: utf-8 -*-

import requests


####################################日志部分##############################################
#监控模块
from utils import logutils
logger=logutils.getlogger(__file__)
######################################################################################

#登录验证装饰器
def loginreqired(func):
    def wrapper(self, *args, **kwargs):
        cookies = self.browser.get_cookies()
        if not cookies:
            logger.info('装饰器检测到未登录，先登录系统')
            self.dologin()
        rdata = func(self, *args, **kwargs)
        return rdata
    return wrapper

#登录验证装饰器
def cookiesreqired(func):
    def wrapper(self, *args, **kwargs):

        cookies_browser= self.browser.get_cookies()
        cookies_browser_sessionid=None
        cookies_browser_csrftoken=None
        cookies_browser_JSESSIONID=None

        for item in cookies_browser:
            if item['name']== 'sessionid':
                cookies_browser_sessionid=item['value']
            if item['name']== 'csrftoken':
                cookies_browser_csrftoken=item['value']
            if item['name']== 'JSESSIONID':
                cookies_browser_JSESSIONID=item['value']
        reload_cookies = False
        if not self.httpsession.cookies:
            reload_cookies=True
        else:
            tmpdict = requests.utils.dict_from_cookiejar(self.httpsession.cookies)

            if 'JSESSIONID' in tmpdict and tmpdict['JSESSIONID'] != cookies_browser_JSESSIONID:
                reload_cookies = True
            if 'csrftoken' in tmpdict and tmpdict['csrftoken'] != cookies_browser_csrftoken:
                reload_cookies = True
            if 'sessionid' in tmpdict and tmpdict['sessionid'] != cookies_browser_sessionid:
                reload_cookies = True
        if reload_cookies:
            logger.info('装饰器检测到未装载cookie，先装载cookie')
            # self.loadcookie()
            self.newloadcookie()
        rdata = func(self, *args, **kwargs)
        return rdata
    return wrapper
